package org.example;

import opennlp.tools.langdetect.LanguageDetectorME;
import opennlp.tools.langdetect.LanguageDetectorModel;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class LanguageDetectionService {
    private LanguageDetectorME languageDetector;

    public LanguageDetectionService() {
        try (InputStream modelIn = new FileInputStream("nlp1/langdetect-183.bin")) {
            LanguageDetectorModel model = new LanguageDetectorModel(modelIn);
            languageDetector = new LanguageDetectorME(model);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String detectLanguage(String text) {
        try {
            return languageDetector.predictLanguage(text).getLang();
        } catch (Exception e) {
            return "Unknown";
        }
    }
}
